package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.controller.admin.resp.AdminStatOrder;
import com.wcs.exam.controller.admin.resp.AdminStatOrderInfo;
import com.wcs.exam.dao.OrderInfoDao;
import com.wcs.exam.dao.impl.mapper.OrderInfoMapper;
import com.wcs.exam.dao.impl.mapper.entity.OrderInfo;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 订单信息 持久化实现类
 *
 * @author wcs
 * @since 2025-03-17
 */
@Repository
public class OrderInfoDaoImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoDao {

    @Override
    public <R> List<R> selectObjs(Wrapper<OrderInfo> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        return lambdaQuery()
                .eq(OrderInfo::getOrderNo, orderNo)
                .last(SqlUtil.limitOne())
                .one();
    }

    @Override
    public AdminStatOrder stat(Long userId) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.select("count(id) as courseBuySum, sum(paid_amount) as courseBuyMoney");
        wrapper.lambda()
                .eq(OrderInfo::getOrderStatus, 2)
                .eq(ObjectUtil.isNotEmpty(userId), OrderInfo::getUserId, userId);
        return selectObjs(wrapper, AdminStatOrder.class).get(0);
    }

    @Override
    public List<AdminStatOrderInfo> stat(String startDate, String endDate) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.select("DATE_FORMAT(pay_time, '%Y-%m-%d') as dates, count(id) as orders, sum(paid_amount) as moneys");
        wrapper.lambda().eq(OrderInfo::getOrderStatus, 2)
                .ge(StringUtils.hasText(startDate), OrderInfo::getPayTime, startDate)
                .lt(StringUtils.hasText(endDate), OrderInfo::getPayTime, endDate);
        wrapper.groupBy("dates");
        return selectObjs(wrapper, AdminStatOrderInfo.class);
    }
}
